#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include "aes.h"
#include "util.h"

int
decryptAES(char *cryptedText, int len, char *key)
{
    EVP_CIPHER_CTX ctx;
    char iv[16];
    char final[EVP_MAX_BLOCK_LENGTH];
    char plain[MAX_SECRET_SIZE]={0};
    int finalLen;
	
    memset(iv, 0, 16);
	
    if (key == NULL)
    {
        fprintf(stderr, "Fatal error: key cannot be null\n");
        exit(EXIT_FAILURE);
    }
	
    if (cryptedText == NULL)
    {
        fprintf(stderr, "Fatal error: crypted text cannot be null\n");
        exit(EXIT_FAILURE);
    }
	
    /* inicializar */
    EVP_CIPHER_CTX_init(&ctx);
	
    EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
					   (unsigned char *)key, (unsigned char *)iv);
    //setup_decryption(&ctx, key, iv);
    decrypt(&ctx, cryptedText, len, plain);
	
    if (plain != NULL)
    {
        if (!checkASCII(plain, strlen(plain))) {
			EVP_CIPHER_CTX_cleanup(&ctx);
            return 0;
		}
    }
	
    if (!EVP_DecryptFinal_ex(&ctx, (unsigned char *)final, &finalLen))
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return 0;
    }
	
    final[finalLen] = 0;
	
    printf("%s", plain);
    printf("%s\n", final);
	
    EVP_CIPHER_CTX_cleanup(&ctx);
	
    return 1;
}

char *
decrypt(EVP_CIPHER_CTX *ctx, char *ct, int inl, char *pt)
{
    int ol;
	
    EVP_DecryptUpdate(ctx, (unsigned char *)pt, &ol, (unsigned char *)ct, inl);
    if (!ol)
    {
        /* no hay bloque para descifrar */
        return NULL;
    }
    pt[ol] = 0;
	
    return pt;
}
